define([
  'text',
  't',
  './sass',
  'hy5b/frontend/path/path'
], function(text, ttt, Sass, path) {

  var head = document.getElementsByTagName('head')[0];

  var styleCnt = 0;
  var curStyle;
  var inject = function(css) {
    if (styleCnt < 31) {
      curStyle = document.createElement('style');
      curStyle.type = 'text/css';
      head.appendChild(curStyle);
      styleCnt++;
    }
    if (curStyle.styleSheet)
      curStyle.styleSheet.cssText += css;
    else
      curStyle.appendChild(document.createTextNode(css));
  }
  var workerUrl = path.resolve(path.dirname(require.toUrl('scss')), "./sass.worker.js");
  var sass = new Sass(workerUrl);

  var regexImport = /@import ['"]([^'"]*)['"]/;

  var parseImport = function(name, absUrl, toUrl, callback) {
    
    text.get(absUrl, function(data) {
      var ret = ttt.matchAll(data, regexImport);
      if (ret.length > 0) {
        sass.writeFile(name, data, function() {
          console.warn(`sass worker wrote "${name}"`);
        });
        
        var subName = ret[0].match[1];
        var subAbsUrl = toUrl(subName);
        if (subAbsUrl.charAt(0) !== '/') {
          subAbsUrl = path.resolve(path.dirname(absUrl), subName);
        }
        parseImport(subName, subAbsUrl, toUrl, function() {
          callback();
        })
      } else {
        sass.writeFile(name, data, function() {
          console.warn(`sass worker wrote "${name}"`);
        });
        callback();
      }
    })
  }
  
  return {
    load: function (name, parentRequire, onload, config) {
      var absUrl = parentRequire.toUrl(name);

      parseImport(name, absUrl, parentRequire.toUrl, function callback() {

        sass.options({ style: Sass.style.expanded }, function(result) {
          console.warn("sass worker set options");
        });

        sass.compile(`@import "${name}";`, function(result) {
          if (result.status !== 0) {
            console.error(result.formatted);
            onload();
            return
          }
          inject(result.text);
          setTimeout(onload, 7);
        });
      })
      
    }
  }
})